import java.util.LinkedList;
import java.util.List;

/**
 * 77. 组合
 * https://leetcode.cn/problems/combinations/description/
 */
class Solution2 {
    List<List<Integer>> ret;
    List<Integer> path;
    boolean[] check;
    int k, n;

    public List<List<Integer>> combine(int _n, int _k) {
        ret = new LinkedList<>();
        path = new LinkedList<>();
        n = _n; k = _k;
        check = new boolean[n + 1];

        dfs(1);

        return ret;
    }

    public void dfs(int pos) {
        if(path.size() == k) {
            ret.add(new LinkedList<>(path));
            return;
        }

        for(int i = 1; i <= n; i++) {
            if(!check[i] && pos >= i) {
                path.add(i);
                check[i] = true;
                dfs(pos + 1);
                check[i] = false;
                path.remove(path.size() - 1);
            }
        }

    }
}